﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq.SqlClient;
using S9Engine;


public partial class User : Parser
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            InitAll();

            if (!CheckLogin()) Response.Redirect("login.aspx");

            _parser.SetCurrentDir("~/html");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            Session["CurrentPage"] = "User.aspx";

            if ((Session["UserType"] == null) || (Session["UserType"] as string != "Administrator"))
            {
                LoadFile("user.html", false);
                _parser.Parse("Main.NoneAdmin");
            }
            else
            {
                string type = Request["type"] ?? "default";

                _DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Users);

                switch (type)
                {
                    case "default":
                        {
                            LoadFile("user.html", false);
                            LoadUsers();
                            break;
                        }
                    case "add":
                        {
                            LoadFile("user_add.html", false);
                            LoadUserByID(null);
                            break;
                        }
                    case "classify":
                        {
                            if (Request["id"] == null)
                            {
                                Response.Redirect("user.aspx");
                            }
                            else
                            {
                                LoadFile("user_classify.html", false);
                                LoadUserClassifications(long.Parse(Request["id"]));
                            }
                            break;
                        }
                    case "edit":
                        {
                            if (Request["id"] == null)
                            {
                                Response.Redirect("user.aspx");
                            }
                            else
                            {
                                LoadFile("user_add.html", false);
                                LoadUserByID(long.Parse(Request["id"]));
                            }
                            break;
                        }
                    case "delete":
                        {
                            if (Request["id"] == null)
                            {
                                Response.Redirect("user.aspx");
                            }
                            else
                            {
                                DeleteUserByID(long.Parse(Request["id"]));
                            }
                            break;
                        }
                    default: goto case "default";
                }
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void LoadUsers()
    {
        try
        {
            List<Users> users = _DR.Users.Where(u => u.LanguageCode.Equals(_currentLanguage) || u.Type.Equals("Administrator")).OrderBy(u => u.Username).OrderBy(u => u.ID).ToList();

            string search = Request["search"] ?? string.Empty;

            if (!string.IsNullOrEmpty(search))
            {
                users = users.Where(t => t.Fullname.Contains(search) || t.Username.Contains(search)).ToList();
                _parser.Assign("searchValue", search);
            }

            double totalRecord = users.Count();
            int page = int.Parse(Request["page"] ?? "1");
            int pageSize = _rowsPerPage;
            int totalPage = (int)(totalRecord / pageSize);
            
            if (totalPage * pageSize < totalRecord) totalPage++;

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * pageSize));
                int endRecord = (int)(page * pageSize > totalRecord ? totalRecord : page * pageSize);

                for (int i = startRecord; i < endRecord; i++)
                {
                    _parser.Assign("userID", users[i].ID.ToString());
                    _parser.Assign("userName", users[i].Username);
                    _parser.Assign("userFullName", users[i].Fullname);
                    _parser.Assign("userType", _parser.GetLabelValue(users[i].Type, _currentLanguage));
                    _parser.Parse("Main.Content.Table.TableItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / _pageRange;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % _pageRange == (_pageRange - 1) && page > _pageRange)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * _pageRange == 0 ? 1 : pagingPage * _pageRange);
                    }

                    endPage = (startPage + (_pageRange - 1) > totalPage ? totalPage : startPage + (_pageRange - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());


                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("currentPageStyle", page == i ? " class=\"current\"" : string.Empty);

                        if (!string.IsNullOrEmpty(search)) _parser.Assign("searchInfo", string.Format("&search={0}", search));

                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.Content.Table.Paging.PagingItem");
                    }

                    _parser.Parse("Main.Content.Table.Paging.PagingPrevious");
                    _parser.Parse("Main.Content.Table.Paging.PagingNext");
                }

                _parser.Parse("Main.Content.Table.Paging");
                _parser.Parse("Main.Content.Table");
            }
            
            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LoadUserByID(long? ID)
    {
        try
        {
            if (ID == null) //AddNew
            {
                _parser.Assign("userName", string.Empty);
                _parser.Assign("password", string.Empty);
                _parser.Assign("userFullName", string.Empty);
                _parser.Parse("Main.Content.EditForm.AddNew");
                _parser.Parse("Main.Content.EditForm");
                _parser.Parse("Main.AddNewUser");
            }
            else //Edit
            {
                Users user = _DR.Users.Where(t => t.ID.Equals(ID.Value)).FirstOrDefault();

                if (user == null)
                {
                    _parser.Parse("Main.Content.Error");
                }
                else
                {
                    _parser.Assign("userID", user.ID.ToString());
                    _parser.Assign("userUserName", user.Username);
                    _parser.Assign("userPassword", user.Password);
                    _parser.Assign("userFullName", user.Fullname);
                    _parser.Assign("userType", user.Type);

                    _parser.Parse("Main.Content.EditForm.Edit");
                    _parser.Parse("Main.Content.EditForm.ConfirmPassword");
                    _parser.Parse("Main.Content.EditForm");
                    _parser.Parse("Main.EditUser");
                }
            }
            
            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteUserByID(long ID)
    {
        try
        {
            Users user = _DR.Users.Where(u => u.ID.Equals(ID)).FirstOrDefault();

            if (user != null)
            {
                _DR.DeleteObject(user);
                _DR.SaveChanges();
            }

            Response.Redirect("user.aspx");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LoadUserClassifications(long ID)
    {
        try
        {
            bool exist = _DR.Permission.Where(p => p.User.Equals(ID)).Count() > 0;
            Users user = _DR.Users.Where(u => u.ID.Equals(ID)).FirstOrDefault();

            if (user.Type == "Administrator") Response.Redirect("user.aspx");

            List<SelectCategory> selectCategory = (from term in _DR.Terms
                                                   join taxonomy
                                                       in _DR.Taxonomy on term.ID equals taxonomy.Term
                                                   where taxonomy.Name.Equals("news-category") && taxonomy.LanguageCode.Equals(_currentLanguage)
                                                   select new SelectCategory()
                                                   {
                                                       ID = term.ID,
                                                       Name = term.Name,
                                                       Parent = taxonomy.Parent
                                                   }).ToList();

            BuildSelectCategory = (ParentId, Level) =>
            {
                return (from c in selectCategory
                        where c.Parent == ParentId
                        from t in new List<SelectCategory>()
                        {
                            new SelectCategory()
                            {
                                ID = c.ID,
                                Name = new String('-', Level) + c.Name,
                                Parent = c.Parent
                            }
                        }.Union(BuildSelectCategory(c.ID, Level + 1))
                        select t).ToList();
            };

            selectCategory = BuildSelectCategory(0, 0);

            foreach (SelectCategory s in selectCategory)
            {
                _parser.Assign("categoryID", s.ID.ToString());
                _parser.Assign("categoryName", s.Name.Replace("-", string.Empty));
                _parser.Assign("categoryURL", "~/../category.aspx?id=" + s.ID.ToString());
                _parser.Assign("position", s.Name.IndexOf("-") == -1 ? string.Empty : " style=\"padding-left:" + (s.Name.LastIndexOf("-") + 1) + "em!important\"");
                _parser.Parse("Main.Content.Table.CategoryList.CategoryListItem");
            }

            if (selectCategory.Count != 0) _parser.Parse("Main.Content.Table.CategoryList");

            _parser.Assign("userID", user.ID.ToString());

            if (exist)
            {
                Permission permission = _DR.Permission.Where(p => p.User.Equals(ID) && p.Type.Equals("function")).FirstOrDefault();

                _parser.Assign("viewFunction", permission == null ? string.Empty : permission.Read);
                _parser.Assign("editFunction", permission == null ? string.Empty : permission.Write);

                permission = _DR.Permission.Where(p => p.User.Equals(ID) && p.Type.Equals("category")).FirstOrDefault();

                _parser.Assign("viewCategory", permission == null ? string.Empty : permission.Read);
                _parser.Assign("editCategory", permission == null ? string.Empty : permission.Write);

                _parser.Parse("Main.SelectItem");

                permission = null;
            }
            else
            {
                _parser.Parse("Main.FullControl");
            }

            _DR.SaveChanges();

            _parser.Parse("Main.Content.Table");
            _parser.Parse("Main.Content");

            user = null;
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
}